package com.zlc.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * 文件处理工具
 */
public class FileUtil {

    /**
     * 文件上传
     * @param path   上传路径
     * @param fileName 文件名称
     * @param inputStream 文件流
     * @return  目录
     */
    public static String upload(String path, String fileName, InputStream inputStream) {
        // 创建目标目录
        File directory = new File(path);
        if (!directory.exists()) {
            directory.mkdirs();
        }

        // 构造完整文件路径
        String fullPath = path + "/" + fileName;
        File file = new File(fullPath);

        // 保存文件流到指定目录
        try (FileOutputStream outputStream = new FileOutputStream(file)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return fullPath;
    }

    /**
     * 使用NIO方式上传文件（替代实现）
     * @param path   上传路径
     * @param fileName 文件名称
     * @param inputStream 文件流
     * @return  目录
     */
    public static String uploadWithNIO(String path, String fileName, InputStream inputStream) {
        try {
            // 创建目标目录
            Path directory = Paths.get(path);
            if (!Files.exists(directory)) {
                Files.createDirectories(directory);
            }

            // 构造完整文件路径并复制文件
            Path targetPath = directory.resolve(fileName);
            Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);

            return targetPath.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
